﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

using Telerik.Cms.Engine;

namespace Telerik.Sitefinity.Services.Migration
{
	public partial class MigrationExportService : IMigrationExportService
	{
		public Message GetGenericContentList()
		{
			List<MigrationItemContentDefinition> output = new List<MigrationItemContentDefinition>();

			foreach (KeyValuePair<string, ContentProviderBase> provider in m_AllProviders)
			{
				// Use direct type comparison, since all providers inherit from Providers.DefaultProvider
				if (provider.Value.GetType().ToString() == "Telerik.Cms.Engine.Data.Providers.DefaultProvider")
				{
					string providerName = provider.Key;
					ContentManager contentManager = new ContentManager(providerName);

					if (provider.Value.AllowLocalization)
					{
						foreach (var culture in m_Cultures)
						{
							System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(culture);

							IList genericContentItems = contentManager.GetContent();
							AddGenericContentGuidToList(genericContentItems, output, providerName, culture);
						}
					}
					else
					{
						IList genericContentItems = contentManager.GetContent();
						AddGenericContentGuidToList(genericContentItems, output, providerName, String.Empty);
					}
				}
			}

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetGenericContentListResponse", output);
		}

		public Message GetSingleGenericContent(Message genericContentDefinitionParam)
		{
			MigrationItemContentDefinition param = genericContentDefinitionParam.GetBody<MigrationItemContentDefinition>();

			ContentManager contentManager = new ContentManager(param.ProviderName);
			if (!String.IsNullOrEmpty(param.Language))
				System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(param.Language);
			IContent genericContent = contentManager.GetContent(param.Id);

			MigrationGenericContent result = new MigrationGenericContent();

			GetSingleGenericContentItem(result, genericContent, param.ProviderName, param.Language);

			MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
			return Message.CreateMessage(ver, "GetSingleGenericContentResponse", result);
		}
	}
}
